
/**
 * @file AppContext.tsx
 * @description 应用上下文管理，处理应用安装卸载相关的状态和通信
 */

'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';

interface AppItem {
  key: string;
  label: string;
  icon: string;
  href: string;
  description?: string;
}

interface AppContextType {
  installedApps: string[];
  installApp: (app: AppItem) => void;
  uninstallApp: (key: string) => void;
}

const STORAGE_KEY = 'installed_apps';

const AppContext = createContext<AppContextType | undefined>(undefined);

export function AppProvider({ children }: { children: ReactNode }) {
  const [installedApps, setInstalledApps] = useState<string[]>([]);

  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      setInstalledApps(JSON.parse(stored));
    }
  }, []);

  const installApp = (app: AppItem) => {
    const newInstalledApps = [...installedApps, app.key];
    setInstalledApps(newInstalledApps);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(newInstalledApps));
  };

  const uninstallApp = (key: string) => {
    const newInstalledApps = installedApps.filter(k => k !== key);
    setInstalledApps(newInstalledApps);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(newInstalledApps));
  };

  return (
    <AppContext.Provider value={{ installedApps, installApp, uninstallApp }}>
      {children}
    </AppContext.Provider>
  );
}

export function useApp() {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useApp must be used within an AppProvider');
  }
  return context;
} 